<template>
  <div class="geofence-container">
    <div class="map-container">
      <ReMap ref="mapRef" :center="[39.9042, 116.4074]" :zoom="13" />
    </div>
    <div class="control-panel">
      <h3>电子围栏管理</h3>
      <el-button-group>
        <el-button
          type="primary"
          :disabled="state !== 'idle'"
          @click="startDrawing('polygon')"
        >
          <el-icon><Edit /></el-icon> 绘制围栏
        </el-button>
        <el-button type="success" :disabled="!currentFence" @click="saveFence">
          <el-icon><Check /></el-icon> 保存围栏
        </el-button>
        <el-button
          type="danger"
          :disabled="state === 'idle' || !currentFence"
          @click="cancelDrawing"
        >
          <el-icon><Close /></el-icon> 取消
        </el-button>
      </el-button-group>

      <div class="fence-list">
        <h4>已保存围栏</h4>
        <el-list v-if="fences.length > 0" :data="fences">
          <el-list-item v-for="fence in fences" :key="fence.id">
            <div class="fence-item">
              <span>{{ fence.name || `围栏 ${fence.id}` }}</span>
              <el-button size="small" @click="loadFence(fence.id)"
                >加载</el-button
              >
              <el-button
                size="small"
                type="danger"
                @click="deleteFence(fence.id)"
                >删除</el-button
              >
            </div>
          </el-list-item>
        </el-list>
        <p v-else class="empty-tip">暂无保存的围栏</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, Ref } from "vue";
import {
  ElButton,
  ElButtonGroup,
  ElList,
  ElListItem,
  ElInput,
  ElMessage
} from "element-plus";
import { Edit, Check, Close } from "@element-plus/icons-vue";
import ReMap from "@/components/ReMap/index.vue";
import L, { type Map, type LatLngExpression } from "leaflet";
import {
  useMapDrawing,
  type DrawingObject,
  type DrawingState
} from "@/hooks/useMapDrawing";

// 地图引用
const mapRef = ref<InstanceType<typeof ReMap>>();
const mapInstance = ref<Map | null>(null);

// 围栏状态
const currentFence = ref<DrawingObject | null>(null);
const fences = ref<DrawingObject[]>([]);
const state = ref<DrawingState>("idle");
const fenceName = ref("");

// 初始化地图绘制工具
let drawingTools: ReturnType<typeof useMapDrawing>;

onMounted(async () => {
  // 等待地图组件初始化完成
  await nextTick();
  if (mapRef.value?.map) {
    mapInstance.value = mapRef.value.map;
    initDrawingTools();
    loadSavedFences();
  }
});

// 初始化绘制工具
const initDrawingTools = () => {
  if (!mapInstance.value) return;

  // 配置电子围栏样式
  const fenceStyle = {
    polygon: {
      color: "#409EFF",
      weight: 3,
      opacity: 0.8,
      fillColor: "#409EFF",
      fillOpacity: 0.2,
      dashArray: "5, 5"
    }
  };

  // 初始化地图绘制工具
  drawingTools = useMapDrawing(mapInstance.value, {
    enabledModes: ["polygon", "rectangle", "circle"],
    defaultMode: "polygon",
    style: fenceStyle,
    enableEditing: true,
    enableDeletion: true,
    onDrawComplete: handleFenceDrawn,
    onDrawCancel: () => {
      state.value = "idle";
    },
    onDrawError: error => ElMessage.error(`绘制错误: ${error.message}`)
  });

  // 监听状态变化
  watch(
    () => drawingTools.state,
    newState => {
      state.value = newState;
    }
  );
};

// 开始绘制围栏
const startDrawing = (mode: "polygon" | "rectangle" | "circle") => {
  if (!drawingTools) return;

  // 清除当前未保存的围栏
  if (currentFence.value) {
    drawingTools.stopDrawing();
    currentFence.value = null;
  }

  // 开始新的绘制
  drawingTools.startDrawing(mode);
  ElMessage.info(
    `请在地图上${mode === "polygon" ? "点击绘制多边形" : mode === "rectangle" ? "拖拽绘制矩形" : "点击并拖拽绘制圆形"}`
  );
};

// 处理围栏绘制完成
const handleFenceDrawn = (object: DrawingObject) => {
  if (
    object.type !== "polygon" &&
    object.type !== "rectangle" &&
    object.type !== "circle"
  ) {
    ElMessage.warning("请绘制多边形、矩形或圆形作为电子围栏");
    return;
  }

  currentFence.value = object;
  ElMessage.success("围栏绘制完成，可编辑调整或直接保存");
};

// 保存围栏
const saveFence = () => {
  if (!currentFence.value) return;

  // 使用用户输入的名称或默认名称
  const name = fenceName.value || `电子围栏_${Date.now().toString().slice(-6)}`;
  const newFence = { ...currentFence.value, name };

  // 添加到围栏列表
  fences.value.push(newFence);

  // 保存到本地存储
  localStorage.setItem("geofences", JSON.stringify(fences.value));

  ElMessage.success(`围栏 "${name}" 保存成功`);
  // 重置当前围栏和输入框
  currentFence.value = null;
  fenceName.value = "";
};

// 取消绘制
const cancelDrawing = () => {
  if (drawingTools) {
    drawingTools.stopDrawing();
  }
  currentFence.value = null;
  ElMessage.info("已取消当前围栏绘制");
};

// 加载围栏
const loadFence = (id: string) => {
  const fence = fences.value.find(item => item.id === id);
  if (fence && drawingTools) {
    drawingTools.loadDrawingObject(fence);
    currentFence.value = fence;
    ElMessage.success(`已加载围栏: ${fence.name}`);
  }
};

// 删除围栏
const deleteFence = (id: string) => {
  fences.value = fences.value.filter(item => item.id !== id);
  localStorage.setItem("geofences", JSON.stringify(fences.value));
  // 如果删除的是当前正在编辑的围栏
  if (currentFence.value?.id === id) {
    currentFence.value = null;
    if (drawingTools) drawingTools.clearAll();
  }
  ElMessage.success("围栏已删除");
};
</script>
